package com.example.myapplication15_1;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    // 定义组件对象
    private EditText etName, etProfession;
    private ImageView ivSelectedAvatar;
    private Spinner spinnerAvatar;
    
    // 定义SharedPreferences相关变量
    private SharedPreferences sharedPreferences;
    private static final String PREFS_NAME = "UserInfoPrefs";
    private static final String KEY_NAME = "name";
    private static final String KEY_PROFESSION = "profession";
    private static final String KEY_AVATAR = "avatar";
    
    // 当前选择的头像资源ID
    private String currentAvatarName = "defaultface";
    
    // 头像列表
    private List<String> avatarList = Arrays.asList(
            "defaultface", "dp1", "dp2", "dp3", "dp4", "dp5", 
            "dp6", "dp7", "dp8", "dp9", "dp10");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        // 步骤一：获取各组件对象
        etName = findViewById(R.id.et_name);
        etProfession = findViewById(R.id.et_profession);
        ivSelectedAvatar = findViewById(R.id.iv_selected_avatar);
        spinnerAvatar = findViewById(R.id.spinner_avatar);
        
        // 设置Spinner适配器
        setupAvatarSpinner();
        
        // 步骤二：创建SharedPreferences对象
        sharedPreferences = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        
        // 不再自动读取数据，需要用户点击"读取数据"按钮
    }
    
    // 设置头像选择下拉列表
    private void setupAvatarSpinner() {
        // 创建显示的名称列表
        List<String> displayNames = new ArrayList<>();
        for (int i = 0; i < avatarList.size(); i++) {
            String name = avatarList.get(i);
            if (name.equals("defaultface")) {
                displayNames.add("默认头像");
            } else {
                displayNames.add("头像 " + name.substring(2)); // 去掉"dp"前缀
            }
        }
        
        // 创建适配器
        ArrayAdapter<String> adapter = new ArrayAdapter<>(
                this, android.R.layout.simple_spinner_item, displayNames);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        
        // 设置适配器
        spinnerAvatar.setAdapter(adapter);
        
        // 设置选择监听器
        spinnerAvatar.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                // 更新当前选择的头像
                currentAvatarName = avatarList.get(position);
                updateSelectedAvatar();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // 不做任何处理
            }
        });
    }
    
    // 更新显示的头像
    private void updateSelectedAvatar() {
        // 根据当前头像名称获取资源ID
        int resourceId = getResources().getIdentifier(
                currentAvatarName, "drawable", getPackageName());
        
        // 设置头像
        ivSelectedAvatar.setImageResource(resourceId);
    }
    
    // 设置Spinner选中项
    private void setSpinnerSelection(String avatarName) {
        int position = avatarList.indexOf(avatarName);
        if (position != -1) {
            spinnerAvatar.setSelection(position);
        } else {
            // 如果找不到，设置为默认头像
            spinnerAvatar.setSelection(0);
        }
    }
    
    // 步骤三：存入数据按钮点击事件
    public void onSaveClick(View view) {
        // 获取用户输入
        String name = etName.getText().toString().trim();
        String profession = etProfession.getText().toString().trim();
        
        // 检查输入是否为空
        if (name.isEmpty() || profession.isEmpty()) {
            Toast.makeText(this, "请填写完整信息", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 获取SharedPreferences编辑器
        SharedPreferences.Editor editor = sharedPreferences.edit();
        
        // 存储数据
        editor.putString(KEY_NAME, name);
        editor.putString(KEY_PROFESSION, profession);
        editor.putString(KEY_AVATAR, currentAvatarName);
        
        // 提交更改
        editor.apply();
        
        Toast.makeText(this, "数据已保存", Toast.LENGTH_SHORT).show();
    }
    
    // 步骤四：读取数据按钮点击事件
    public void onReadClick(View view) {
        readUserInfo();
    }
    
    // 读取用户信息的方法
    private void readUserInfo() {
        // 检查是否有保存的数据
        if (sharedPreferences.contains(KEY_NAME)) {
            // 读取数据
            String name = sharedPreferences.getString(KEY_NAME, "");
            String profession = sharedPreferences.getString(KEY_PROFESSION, "");
            currentAvatarName = sharedPreferences.getString(KEY_AVATAR, "defaultface");
            
            // 更新UI
            etName.setText(name);
            etProfession.setText(profession);
            setSpinnerSelection(currentAvatarName);
            updateSelectedAvatar();
            
            Toast.makeText(this, "数据已读取", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "没有保存的数据", Toast.LENGTH_SHORT).show();
        }
    }
    
    // 步骤五：清除数据按钮点击事件
    public void onClearClick(View view) {
        // 清除输入框
        etName.setText("");
        etProfession.setText("");
        
        // 重置头像为默认
        currentAvatarName = "defaultface";
        setSpinnerSelection(currentAvatarName);
        updateSelectedAvatar();
        
        Toast.makeText(this, "界面数据已清除", Toast.LENGTH_SHORT).show();
    }
    
    // 步骤六：删除文件按钮点击事件
    public void onDeleteClick(View view) {
        // 清除SharedPreferences中的所有数据
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.clear();
        editor.apply();
        
        // 尝试删除物理文件
        boolean deleted = deleteSharedPreferencesFile();
        
        // 清除UI
        etName.setText("");
        etProfession.setText("");
        currentAvatarName = "defaultface";
        setSpinnerSelection(currentAvatarName);
        updateSelectedAvatar();
        
        if (deleted) {
            Toast.makeText(this, "数据文件已删除", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "数据已清除", Toast.LENGTH_SHORT).show();
        }
    }
    
    // 删除SharedPreferences文件的方法
    private boolean deleteSharedPreferencesFile() {
        File prefsFile = new File(getApplicationInfo().dataDir + "/shared_prefs/" + PREFS_NAME + ".xml");
        return prefsFile.exists() && prefsFile.delete();
    }
}